<template>
  <div class="search-suggest">
    <van-cell
      :key="index"
      @click="$emit('search',item)"
      icon="search"
      v-for="item,index in searchsuggests"
    >
      <div slot="title" v-html="highlight(item)"></div>
    </van-cell>
  </div>
</template>
<script>
import { getSearchSuggest } from '@/api/search'
import { debounce } from 'lodash'


// function debounce (fn, delay) {
//   // 定时器
//   let timer = null
//   // 将debounce处理结果当作函数返回
//   return function () {
//     // 保留调用时的this上下文
//     let context = this

//     // 保留调用时传入的参数
//     let args = arguments

//     // 每次事件被触发时，都去清除之前的旧定时器
//     if (timer) {
//       clearTimeout(timer)
//     }
//     // 设立新定时器
//     timer = setTimeout(function () {
//       fn.apply(context, args)
//     }, delay)
//   }
// }




export default {
  name: 'SearchSuggest',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      searchsuggests: []
    }
  },
  watch: {
    searchText: {
      // 当searchText 发生变化时 触发handler时间

      handler: debounce(function (value) {
        this.loadSearchSuggest(value)
        // this.loadSearchSuggest(value)
      }, 1000),

      immediate: true
    }
  },
  methods: {
    async loadSearchSuggest (q) {
      try {
        const { data: res } = await getSearchSuggest(q)
        console.log(res);
        this.searchsuggests = res.data.options
      } catch (err) {
        this.$toast('数据获取失败')
      }
    },
    highlight (text) {
      // const str = text
      // const str1 = this.searchText
      // const arr = str.split(str1)
      // return arr.join(`<span class="active">${this.searchText}</span>`)

      const htmlStr = `<span class="active">${this.searchText}</span>`

      // 如果需要根据数据变量动态的创建正则表达式，则手动 new RegExp
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(reg, htmlStr)

    }
  }
}
</script>
<style lang="less" scoped>
.search-suggest {
  /deep/ span.active {
    color: #3296fa;
  }
}
</style>